package com.library.controller;

import com.library.bean.User;
import com.library.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "用户管理")
@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService us; // 注入 UserService 服务类的实例，用于处理业务逻辑

    @ApiOperation(value = "用户注册", notes = "注册新用户")
    @RequestMapping("/register")
    public String register(
            @ApiParam(name = "avatar", value = "用户头像图片") MultipartFile avatar,
            @ApiParam(name = "user", value = "用户信息", required = true) @Valid User user,
            @ApiIgnore BindingResult bindingResult,
            @ApiIgnore Model model) {
        // 如果表单验证有错误
        if (bindingResult.hasErrors()) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors(); // 获取所有字段错误
            Map<String, String> map = new HashMap<>(); // 创建一个 Map 存储字段错误信息
            for (FieldError fieldError : fieldErrors) {
                map.put(fieldError.getField(), fieldError.getDefaultMessage()); // 将字段错误信息放入 Map 中
            }
            model.addAttribute("errors", map); // 将错误信息添加到模型中
            return "forward:/register.jsp"; // 转发到注册页面，显示错误信息
        }

        int result = us.userRegister(user); // 调用 UserService 的 userRegister 方法进行用户注册
        if (result == -1) {
            model.addAttribute("msg", "用户名已经存在"); // 如果用户名已存在，将错误信息添加到模型中
            return "forward:/register.jsp"; // 转发到注册页面，显示错误信息
        }

        if (avatar != null && !avatar.isEmpty() && avatar.getContentType().contains("image")) {
            try {
                String fileName = avatar.getOriginalFilename();// 获取文件原始文件名
                String newName = System.currentTimeMillis() + fileName;
                String savePath = "c:/headImgs/" + newName;// 确定文件存储的路径
                String visitPath = "/22library2/headImgs/" + newName;
                avatar.transferTo(new File(savePath));
                us.updateHeadImg(user.getUsername(), visitPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "forward:/WEB-INF/success.jsp"; // 注册成功，转发到成功页面
    }

    @ApiOperation(value = "用户登录", notes = "用户登录")
    @RequestMapping("/login")
    public String login(
            @ApiParam(name = "user", value = "用户信息", required = true) User user,
            @ApiIgnore Model model,
            @ApiIgnore HttpSession session) {
        Map<String, Object> map = us.userLogin(user);
        if (map.containsKey("loginUser")) {
            session.setAttribute("loginUser", map.get("loginUser"));
            return "redirect:/books";
        }
        model.addAttribute("msg", map.get("msg"));
        return "forward:/login.jsp";
    }
}